<?php

namespace app\admin\controller;

use think\Controller;

// 后台admin控制器
class Index extends Controller
{

    // 初始化方法
    public function initialize()
    {
        if (session('?admin.id')){
            $this->redirect('admin/home/index');
        }
    }

    //后台登录
    public function login()
    {
        // 判断是否ajax提交
        if (request()->isAjax()) {
            // $data接收登录页post提交的数据
            $data = [
                'username' => input('post.username'),
                'password' => input('post.password')
            ];
            // 进行登录验证
            $valid_result = model('Admin')->login($data);
            if ($valid_result == 1) {    //登录验证通过
                // 跳转到后台首页
                $this->success('登录成功', 'admin/home/index');
            } else {  //登录失败
                // 返回错误信息
                $this->error($valid_result);
            }
        }

        // get提交时返回登录页面视图
        return view();
    }


    // 用户注册
    public function register()
    {
        if (request()->isAjax()) {
            $data = [
                'username' => input('post.username'),
                'password' => input('post.password'),
                're_password' => input('post.re_password'),
                'nickname' => input('post.nickname'),
                'email' => input('post.email'),
            ];
            $valid_result = model('Admin')->register($data);
            if ($valid_result == 1) {    //注册验证成功
                $this->success('注册成功', 'admin/index/login');
            } else {  //注册失败
                $this->error($valid_result);
            }
        }


        // get
        return view();
    }


    // 忘记密码，发送验证码
    public function forget()
    {
        if (request()->isAjax()){
            // 生成随机验证码
            $code = mt_rand(10000,99999);
            // 成本验证码到session
            session('code', $code);
            $result = send_email(input('post.email'), '重置密码验证码', '您的验证码为：'.'<b>'.$code.'</b>');
            if ($result){
                $this->success('验证码发送成功');
            }else{
                $this->error('验证码发送失败');
            }
        }

        return view();
    }

    // 重置密码
    public function reset(){
        if (request()->isAjax()){
            $data = [
                'code' => input('post.code'),
                'email' => input('post.email')
            ];
            $result = model('Admin')->reset($data);
            if ($result == 1){
                $this->success('重置密码成功，请去邮箱查看新密码');
            }else{
                $this->error($result);
            }
        }else{
            return;
        }
    }

}
